package com.codefish.codefish_blog.config.interceptors;

import com.codefish.codefish_blog.config.property.BlogWebProperties;
import com.codefish.codefish_blog.entity.User;
import com.codefish.codefish_blog.utils.CookieUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 检查用户登录情况的拦截器
 *
 * @author codefish
 * @version 1.0
 * @date 2022/04/11 下午 08:51
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        //获取key为userInfo的cookie的值
        String userInfo = CookieUtil.getValueByKey(request, BlogWebProperties.USER_INFO_PROPERTY);
        if (!StringUtils.isEmpty(userInfo)) {
            if (session.getAttribute(BlogWebProperties.USER_INFO_PROPERTY) != null) {
                return true;
            }
            String[] strs = userInfo.split("_");
            User user = new User();
            user.setId(Integer.parseInt(strs[0]));
            user.setUsername(strs[1]);
            session.setAttribute(BlogWebProperties.USER_INFO_PROPERTY, user);
        } else {
            session.removeAttribute(BlogWebProperties.USER_INFO_PROPERTY);
        }
        return true;
    }
}
